package com.stu.controller.valida;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author zhuzi
 * 2022/8/23 11:22
 */
@Api(tags = "单个参数校验")
@Slf4j
@Validated
@RestController
@RequestMapping("/valid/single")
public class SingleParamController {
    /**
     * 单个参数校验，需要在类上添加 @Validated 。 https://zhuanlan.zhihu.com/p/387010936
     *
     * @param name
     * @param code
     * @return
     */
    @ApiOperation(value = "校验单个参数", notes = "校验单个参数测试")
    @GetMapping("param")
    public String param(@Length(min = 3, message = "名字最小长度") @RequestParam String name, @Length(max = 5, message = "编码长度不能超过20") @RequestParam String code) {
        return StringUtils.repeat(name, 2) + code;
    }

    @ApiOperation(value = "校验集合非空", notes = "校验单个参数测试")
    @GetMapping("list")
    public String list(@NotEmpty(message = "集合不能为空") @RequestParam List<String> name) {
        System.out.println(Thread.currentThread().getName());
        if (CollectionUtils.isNotEmpty(name)) {
            name.stream().forEach(vo -> System.out.println(vo));
        }
        return StringUtils.repeat("name", 2);
    }

    @ApiOperation(value = "long非空校验", notes = "校验单个参数测试")
    @GetMapping("long")
    public String longs(@NotNull(message = "不能为空") Long id) {
        System.out.println(Thread.currentThread().getName());
        System.out.println("" + id);
        return StringUtils.repeat("name", 2);
    }
}
